import axios from 'axios'
import router from '../router'
import message from './message'
import store from '../store'
import * as constConfig from "../constData/ConstData";

axios.defaults.timeout = 5000
axios.defaults.headers['X-Request-With'] = 'XMLHttpRequest'
axios.defaults.headers['Cache-Control'] = 'no-cache'
axios.defaults.headers['Content-Type'] = constConfig.contentTypeJson

let count = 0 //发出请求的计数器
let requestList = new Set() //存储url

axios.interceptors.request.use(config => {
    config.cancelToken = new axios.CancelToken(() => {
        requestList.has(config.url) ? message.error("请勿重复请求") : requestList.add(config.url)
    }) //阻止重复提交请求
    store.commit('showLoading', true)//开启加载动画
    count++
    axios.defaults.headers[constConfig.tokenHeader] = localStorage.getItem(constConfig.tokenHeader)
    axios.defaults.headers[constConfig.refreshTokenHeader] = localStorage.getItem(constConfig.refreshTokenHeader)
    return config
}, () => {
    requestList = new Set()
    store.commit('showLoading', false)
    message.error("请求超时");
    return Promise.reject("请求超时");
})


axios.interceptors.response.use(response => {
        count--
        setTimeout(() => {
            requestList.delete(response.config.url)
        }, 600)
        if (count <= 0) {
            store.commit('showLoading', false)
        }
        let res = response.data
        if (res.code === 200) {
            //如果返回值中携带token,则进行存储
            const authToken = response.headers[constConfig.tokenHeader.toLowerCase()]
            const refreshToken = response.headers[constConfig.refreshTokenHeader.toLowerCase()]
            if (authToken !== undefined && refreshToken !== undefined) {
                store.commit('SET_AUTH_TOKEN', authToken)
                store.commit('SET_REFRESH_AUTH_TOKEN', refreshToken)
            }
            return response
        } else {
            message.error(!res.data ? '系统异常' : res.data)
            return Promise.reject(response.data.message)
        }
    }, error => {
        requestList = new Set()
        store.commit('showLoading', false)
        if (error.message) {
            error.message = error.message ? '请求异常' : error.message
        }
        setTimeout(() => {
            router.push("/").then(() => {})
        }, 1000);
        message.error(error.message)
        return Promise.reject(error)
    }
)

export default axios
